import numpy as np
import time
from moviepy.editor import VideoFileClip


def calculate_audio_video_sync(video_path, max_duration=50):
    # 加载视频文件
    video = VideoFileClip(video_path)

    # 获取视频的帧率
    fps = video.fps

    # 获取视频的总时长（秒）
    video_duration = video.duration

    # 获取音频的采样率
    audio_sample_rate = video.audio.fps if video.audio else 0

    # 计算视频和音频的时间戳
    video_time_stamps = np.arange(0, video_duration, 1 / fps)
    audio_time_stamps = np.arange(0, video.audio.duration, 1 / audio_sample_rate) if video.audio else []

    # 计算总的检测点数量
    total_points = min(len(video_time_stamps), len(audio_time_stamps))

    # 用于存储已检测的索引
    checked_indices = set()

    # 用于存储时间差
    time_differences = []

    # 记录开始时间
    start_time = time.time()

    while len(checked_indices) < total_points:
        # 检查是否超过最大执行时间
        if time.time() - start_time > max_duration:
            print("Reached maximum duration for detection. Exiting loop.")
            break

        # 随机选择3个未检测的索引
        remaining_indices = list(set(range(total_points)) - checked_indices)
        if len(remaining_indices) < 3:
            sample_indices = remaining_indices  # 如果剩余少于3个，全部取出
        else:
            sample_indices = np.random.choice(remaining_indices, size=3, replace=False)

        # 计算时间差
        for i in sample_indices:
            time_difference = audio_time_stamps[i] - video_time_stamps[i]
            time_differences.append(time_difference)
            checked_indices.add(i)  # 标记为已检测

    # 计算平均时间差
    if time_differences:
        average_time_difference = np.mean(time_differences)
    else:
        average_time_difference = 0

    # 判断同步程度
    if average_time_difference < -0.2:
        sync_status = "Video is ahead of audio by {:.2f} seconds.".format(abs(average_time_difference))
    elif average_time_difference > 0.2:
        sync_status = "Audio is ahead of video by {:.2f} seconds.".format(average_time_difference)
    else:
        sync_status = "Audio and video are in sync with an average delay of {:.2f} seconds.".format(
            average_time_difference)

    # 输出结果
    print(sync_status)


if __name__ == '__main__':
    # 使用示例
    video_file_path = 'path_to_your_video.mp4'
    calculate_audio_video_sync(video_file_path, max_duration=5)  # 设置最大执行时间为5秒
